package com.zsj.juc.Atomic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/17 14:58
 * @description 原子类属性(对象)修改
 */
class MyVar {
    private static final Logger log = LoggerFactory.getLogger(MyVar.class);

    public volatile Boolean isInit = Boolean.FALSE;

    private static final AtomicReferenceFieldUpdater<MyVar, Boolean> fieldUpdater
            = AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");

    public void init(MyVar var) {
        if (fieldUpdater.compareAndSet(var, false, true)) {
            log.info("{}\t----start init", Thread.currentThread().getName());
        } else {
            log.info("{}\t----already init ed", Thread.currentThread().getName());
        }
    }
}

public class AtomicReferenceFieldUpdaterDemo {

    public static void main(String[] args) {

        MyVar myVar = new MyVar();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myVar.init(myVar);
            }, i + "").start();
        }
    }

}
